package com.softeem.mpdemo.controller;

import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.softeem.mpdemo.dto.MusicDetails;
import com.softeem.mpdemo.dto.Result;
import com.softeem.mpdemo.entity.Ablum;
import com.softeem.mpdemo.entity.Music;
import com.softeem.mpdemo.entity.Singer;
import com.softeem.mpdemo.service.AblumService;
import com.softeem.mpdemo.service.MusicService;
import com.softeem.mpdemo.service.SingerService;
import com.softeem.mpdemo.utils.QiniuOssUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Tag(name = "音乐管理",description = "音乐上传，列表，检索，更新，删除下架等操作")
@CrossOrigin
@RestController
public class MusicController {

    @Autowired
    private MusicService musicService;
    @Autowired
    private AblumService ablumService;
    @Autowired
    private SingerService singerService;

    @Operation(summary = "文件上传",description = "上传音乐文件，以及音乐文本信息")
    @Parameters({
            @Parameter(name = "music",description = "音乐文本信息，包含:名称,专辑id,流派,歌词,播放时长等"),
            @Parameter(name = "myfile",description = "上传的文件对象")
    })
    @PostMapping("/music/upload")
    public Result upload(Music music, MultipartFile myfile) throws IOException {
        //文件名
        String fname = myfile.getOriginalFilename();
        //文件大小
        long size = myfile.getSize();
        //上传到服务端的文件流（字节输入流）
        InputStream is = myfile.getInputStream();
        //创建key(文件的唯一标识)
        String key = UUID.randomUUID().toString();
        //创建七牛工具
        QiniuOssUtils utils = new QiniuOssUtils();
        //执行上传并且获取返回的文件地址
        String path = utils.upload(is, key);
        //将文件信息赋值到歌曲对象中
        music.setSize((int)size);
        music.setPath(path);
        //执行持久化操作
        if(musicService.save(music)){
            return Result.ok().setMsg("上传成功").setData(music);
        }
        //删除已上传的文件
        utils.delete(key);
        return Result.fail().setMsg("上传失败");
    }


    @Operation(summary = "音乐分页查询",description = "通过提供的页码与每页大小查询指定页歌曲数据")
    @Parameters({
            @Parameter(name = "page",description = "当前查询页码"),
            @Parameter(name = "limit",description = "每页数据行数")
    })
    @GetMapping("/music/list")
    public Result list(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "5") Integer limit){
        //执行分页查询
        List<Music> list = musicService.list(new Page<Music>(page, limit));
        List<MusicDetails> details = listConvertor(list);
        //获取总数据行数，执行前端分页时使用
        long count = musicService.count();
        return Result.ok().setMsg("查询成功").setData(details).setCount((int)count);
    }

    @Operation(summary = "根据歌曲名称查询",description = "模糊查询，提供关键字即可实现")
    @GetMapping("/music/query")
    public Result query(@Parameter(description = "歌曲名关键字") String key){
        // where name like '%key%'
        QueryWrapper<Music> query = Wrappers.query(Music.class);
        query.like("name",key);
        //执行模糊查询
        List<Music> list = musicService.list(query);
        //根据条件查询符合条件的总数
        long count = musicService.count(query);
        //List<Music>  =>  List<MusicDetails>
        List<MusicDetails> details = listConvertor(list);
        return Result.ok().setMsg("查询完成").setData(details).setCount((int)count);
    }

    /**
     * 集合转换工具，将List<Music>集合转换为List<MusicDetails>集合
     * @param list
     * @return
     */
    private List<MusicDetails> listConvertor(List<Music> list){
        //声明临时变量存储当前页歌曲详情信息
        List<MusicDetails> details = new ArrayList<>();
        //循环遍历歌曲集合，使用子查询查询专辑和歌手数据
        list.forEach(music->{     //lambda表达式（java8新特性） - 语法糖技术
            //获取专辑id
            Integer aid = music.getAid();
            //根据专辑id查询专辑对象
            Ablum ablum = ablumService.getById(aid);

            //获取歌手id
            Integer sid = ablum.getSid();
            //根据歌手id查询歌手对象
            Singer singer = singerService.getById(sid);

            //创建歌曲详情对象
            MusicDetails md = new MusicDetails();
            //转移歌曲信息到详情对象
            md.setId(music.getId());
            md.setName(music.getName());
            md.setUrl(music.getPath());
            md.setStyle(music.getStyle());
            md.setSize(music.getSize());
            md.setDuration(music.getDuration());
            //转移专辑信息到详情对象
            md.setAblumName(ablum.getName());
            md.setAblumImg(ablum.getCoverimg());
            md.setReleasetime(ablum.getReleasedate());
            //转移歌手信息到详情对象
            md.setSingerName(singer.getName());
            //将歌曲详情对象加入集合中
            details.add(md);
        });
        return details;
    }
}
